import Vue from 'vue'
import Router from 'vue-router'
import {checkLogin} from '@/api/login'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'
import {auth, lock, unLock} from '@/utils/auth'

/* Layout */
// import Layout from '@/layout'
// 解决 Avoided redundant navigation to current location: "xxx". 报错
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)
/**
 * Note: 路由配置项
 *
 * hidden: true                   // 当设置 true 的时候该路由不会再侧边栏出现 如401，login等页面，或者如一些编辑页面/edit/1
 * alwaysShow: true               // 当你一个路由下面的 children 声明的路由大于1个时，自动会变成嵌套的模式--如组件页面
 *                                // 只有一个时，会将那个子路由当做根路由显示在侧边栏--如引导页面
 *                                // 若你想不管路由下面的 children 声明的个数都显示你的根路由
 *                                // 你可以设置 alwaysShow: true，这样它就会忽略之前定义的规则，一直显示根路由
 * redirect: noRedirect           // 当设置 noRedirect 的时候该路由在面包屑导航中不可被点击
 * name:'router-name'             // 设定路由的名字，一定要填写不然使用<keep-alive>时会出现各种问题
 * meta : {
    roles: ['admin','editor']    // 设置该路由进入的权限，支持多个权限叠加
    title: 'title'               // 设置该路由在侧边栏和面包屑中展示的名字
    icon: 'svg-name'             // 设置该路由的图标，对应路径src/icons/svg
    breadcrumb: false            // 如果设置为false，则不会在breadcrumb面包屑中显示
  }
 */

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/user/login'),
    meta: {
      title: '登录 · 云雀',
      logged: false
    }
  },
  {
    path: '/register',
    component: () => import('@/views/user/register'),
    meta: {
      title: '注册 · 云雀',
      logged: false
    }
  },
  {
    path: '/todo',
    component: () => import('@/views/workbench/todo'),
    meta: {
      title: '待办任务 · 云雀',
      logged: true,
      menu: true
    }
  },
  {
    path: '/project',
    component: () => import('@/views/workbench/project'),
    meta: {
      title: '项目 · 云雀',
      logged: true,
      menu: true
    }
  },
  {
    path: '/dashboard',
    component: () => import('@/views/workbench/dashboard'),
    meta: {
      title: '用户主页 · 云雀',
      logged: true,
      menu: true
    }
  },
  {
    path: '/document',
    component: () => import('@/views/workbench/document'),
    meta: {
      title: '文档 · 云雀',
      logged: true,
      menu: true
    }
  },
  {
    path: '/password',
    component: () => import('@/views/user/resetPassword'),
    meta: {
      title: '重置密码 · 云雀',
      logged: true
    }
  },
  {
    path: '/user/info',
    component: () => import('@/views/user/userInfo'),
    meta: {
      title: '用户信息 · 云雀',
      logged: true
    }
  },
  {
    path: '/document/:documentUrl',
    component: () => import('@/views/workbench/documentLayout'),
    meta: {
      logged: false
    }
  },
  {
    path: '/search',
    component: () => import('@/views/workbench/search'),
    meta: {
      logged: false,
      menu: true
    }
  },
  {
    path: '/admin',
    component: () => import('@/views/admin'),
    meta: {
      logged: true,
      menu: true
    }
  },
  {
    path: '/404',
    component: () => import('@/views/error/404'),
    meta: {
      title: '404 - Not Found · 云雀',
      logged: false
    }
  },
  {
    path: '/403',
    component: () => import('@/views/error/403'),
    meta: {
      title: '403 - Forbidden · 云雀',
      logged: false
    }
  },
  {
    path: '',
    component: () => import('@/views/index'),
    meta: {
      title: '首页 · 云雀',
      logged: false
    }
  },
  {
    path: '*',
    component: () => import('@/views/error/404'),
    meta: {
      title: '404 - Not Found · 云雀',
      logged: false
    }
  }
]

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

let ALLOW_PATH = {}

for (let constantRoute of constantRoutes) {
  ALLOW_PATH[constantRoute.path] = constantRoute.meta.logged
}

// 标题设置
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.meta.logged) {
    if (!checkLogin()) {
      // 如果登录校验未通过，则尝试获取锁进行重授权
      if (lock()) {
        auth().then(res => {
          store.commit('SET_TOKEN', res.data['accessToken'])
          store.commit('SET_TOKEN_EXPIRED', res.data['expireMills'])
          store.commit('SET_IS_LOGGED', true)
        }).catch(() => {
          store.dispatch('ClearCache').then(() => {
            router.push('/login').then(r => {
              Vue.prototype.$notify.error('未登录或登录已过期，即将跳转到登录页')
            })
          })
        }).finally(() => {
          unLock()
        })
      }
    }
  }
  goNextUrl(to, from, next)
})

function goNextUrl (to, from, next) {
  // 判断是否有标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  window.scrollTo(0, 0)
  // 执行进入路由，如果不写就不会进入目标页
  next()
}

router.afterEach(transition => {
  NProgress.done()
})

export default router
